package com.anysoft.visitdd.example;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

/*rsa解密器*/
public class RsaDecrypter {

    private Cipher mCipher;
    private RSAPrivateKey mPrivateKey;

    public RsaDecrypter(String algorithm, String privateKey) {
        byte[] key_ba;
        try {
            mCipher = Cipher.getInstance(algorithm);
            var keyFactory = KeyFactory.getInstance("RSA");
            key_ba = Base64.getDecoder().decode(privateKey);
            mPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(
                    new PKCS8EncodedKeySpec(key_ba)
            );
            mCipher.init(Cipher.DECRYPT_MODE, mPrivateKey);
        } catch (Exception e) {
            Logger.getGlobal().severe(e.getMessage());
        }
    }

    public String decrypt(String messageE) {
        byte[] message_ba, message_d_ba = null;
        try {
            message_ba = Base64.getDecoder().decode(messageE);
            message_d_ba = ProjectSecurityCommon.rsaDecrypt(mCipher, message_ba);
        } catch (Exception e) {
            Logger.getGlobal().log(Level.SEVERE, "", e);
        }
        return new String(message_d_ba);
    }
}
